package com.channel.temperature.collect.ui.activity

import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.hjq.toast.ToastUtils
import com.hjy.bluetooth.HBluetooth
import com.hjy.bluetooth.entity.BluetoothDevice
import com.hjy.bluetooth.inter.ConnectCallBack
import com.hjy.bluetooth.operator.abstra.Sender
import com.kongzue.dialogx.dialogs.BottomMenu
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kongzue.dialogx.interfaces.OnMenuItemClickListener
import com.channel.temperature.collect.R
import com.channel.temperature.collect.app.base.BaseActivity
import com.channel.temperature.collect.app.ext.initBack
import com.channel.temperature.collect.app.ext.mmkv
import com.channel.temperature.collect.app.util.CRC16Utils
import com.channel.temperature.collect.app.util.MyUtil
import com.channel.temperature.collect.data.annotation.ValueKey
import com.channel.temperature.collect.data.response.SystemInfoBean
import com.channel.temperature.collect.databinding.ActivitySystemSettingBinding
import com.channel.temperature.collect.ui.adapter.TipsAdapter
import com.channel.temperature.collect.ui.viewmodel.SystemSettingModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import me.hgj.mvvmhelper.ext.divider
import me.hgj.mvvmhelper.ext.getColorExt
import me.hgj.mvvmhelper.ext.grid
import me.hgj.mvvmhelper.ext.setOnclickNoRepeat
import me.hgj.mvvmhelper.ext.toStartActivity
import me.hgj.mvvmhelper.util.decoration.DividerOrientation
import java.text.SimpleDateFormat
import java.util.Date


class SystemSettingActivity : BaseActivity<SystemSettingModel, ActivitySystemSettingBinding>() {
    companion object {
        const val TAG = "SystemSettingActivity"
        val baudsListSPP = mutableListOf<String>(
            "9600", "19200", "38400", "57600", "115200", "230400", "460800", "921600"
        )
        val baudsValueListSPP = mutableListOf<Byte>(
            0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07
        )
        val workModeDec = mutableListOf<String>(
            "空闲", "离线", "在线"
        )
        val workModeValue = mutableListOf<Byte>(
            0x00, 0x01, 0x03
        )
    }


    lateinit var dialog: WaitDialog
    lateinit var countDownTimer: CountDownTimer
    private val mTipsAdapter: TipsAdapter by lazy { TipsAdapter() }
    override fun initView(savedInstanceState: Bundle?) {
        //初始化toolbar
        mToolbar.initBack("系统配置") {
            finish()
        }

        mToolbar.setRightDrawable(R.drawable.ic_bluetooth_black_24dp)
        initListener() //初始化 recycleView
        mBind.listRecyclerView.grid(1).divider {
            orientation = DividerOrientation.GRID
            includeVisible = true
            setDivider(0, true)
            setColor(getColorExt(R.color.common_text_hint_color))
        }.adapter = mTipsAdapter
        mBind.systemLayout.visibility = View.GONE
        mBind.ATLayout.visibility = View.VISIBLE
        var flash2Address = 4000
        Log.e(
            "测试值",
            "测试值   " + MyUtil.bytes2Hex(MyUtil.intToBytes(flash2Address)).substring(4, 8)
        )

        mBind.chooseBaudNumber.setText("" + mmkv.getString(ValueKey.baudValueSPP, "9600"))
    }


    override fun onBindViewClick() {
        //1:复位 2：关机 3：唤醒设备 4：进入休眠 5：校时 6：清空flash 7：读取存储数量 8:设备信息 9:写系统参数配置 11：读取时间
        //绑定点击事件
        setOnclickNoRepeat(
            mToolbar.getRightId(),
            mBind.sendSystemCMD,
            mBind.reset,
            mBind.powerOff,
            mBind.wakeUp,
            mBind.enterSleep,
            mBind.readTotalSize,
            mBind.deviceInfo,
            mBind.checkTime,
            mBind.clearTips2,
            mBind.changeToSystemConfig,
            mBind.clearFlash,
            mBind.readSystemCMD,
            mBind.readTime,
            mBind.chooseBaudNumber,
            mBind.setBaudNumber,
            mBind.workModeTypeET,
            mBind.readCheckParameter
        ) {

            when (it) {
                mToolbar.getRightId() -> {
                    var bund = Bundle()
                    bund.putInt(ValueKey.DeviceType, 1)
                    toStartActivity(DeviceListActivity::class.java, bund)
                }

                mBind.workModeTypeET -> {
                    BottomMenu.show(workModeDec as List<CharSequence>?)
                        .setMessage("请选择工作模式").onMenuItemClickListener =
                        OnMenuItemClickListener { dialog, text, index ->
                            mBind.workModeTypeET.text = workModeDec.get(index)
                            false
                        }
                }

                mBind.chooseBaudNumber -> {
                    BottomMenu.show(baudsListSPP as List<CharSequence>?)
                        .setMessage("请选择波特率").onMenuItemClickListener =
                        OnMenuItemClickListener { dialog, text, index ->
                            mBind.chooseBaudNumber.text = baudsListSPP.get(index)
                            mmkv.putString(ValueKey.baudValueSPP, baudsListSPP.get(index))
                            mmkv.putInt(
                                ValueKey.baudValueSPPByte, baudsValueListSPP.get(index).toInt()
                            )
                            false
                        }
                }

                mBind.readCheckParameter -> {

                    if (HBluetooth.getInstance().isConnected) {
                        HBluetooth.getInstance().sender()?.let { it1 ->
                            mViewModel.clickType = 14
                            var cmd = "FF55AA000A" + getAddress() + "4501000010000030"
                            mViewModel.sendCommonCMD(
                                it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                            )
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }

                }

                mBind.setBaudNumber -> {

                    if (HBluetooth.getInstance().isConnected) {
                        HBluetooth.getInstance().sender()?.let { it1 ->
                            mViewModel.clickType = 13
                            var value = mmkv.getInt(ValueKey.baudValueSPPByte, 0)
                            var valueByte = MyUtil.numberToHexOne(value)
                            var cmd = "FF55AA0004" + getAddress() + "48" + valueByte
                            mViewModel.sendCommonCMD(
                                it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                            )
                            ToastUtils.show("设置成功")
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }

                }

                mBind.changeToSystemConfig -> {
                    if (mBind.changeToSystemConfig.text.toString() == getString(R.string.cmd_system)) {
                        mBind.changeToSystemConfig.text = getString(R.string.cmd_other)
                        mBind.systemLayout.visibility = View.VISIBLE
                        mBind.ATLayout.visibility = View.GONE
                    } else {
                        mBind.changeToSystemConfig.text = getString(R.string.cmd_system)
                        mBind.systemLayout.visibility = View.GONE
                        mBind.ATLayout.visibility = View.VISIBLE
                    }
                }

                mBind.clearTips2 -> {
                    mViewModel.clearTips()
                }
                //查询设备系统参数
                mBind.readSystemCMD -> {
                    if (HBluetooth.getInstance().isConnected) {
                        HBluetooth.getInstance().sender()?.let { it1 ->
                            mViewModel.clickType = 9
                            var cmd = "FF55AA000A" + getAddress() + "4501000000000064"
                            mViewModel.sendCommonCMD(
                                it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                            )
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }
                //配置设备系统参数
                mBind.sendSystemCMD -> {
                    if (HBluetooth.getInstance().isConnected) {
                        HBluetooth.getInstance().sender()?.let { it1 ->
                            mViewModel.clickType = 10
                            if (mBind.addressET.text.toString().trim()
                                    .isNullOrBlank() || mBind.timeOutSecondET.text.toString().trim()
                                    .isNullOrBlank() || mBind.wakeUpTimeET.text.toString().trim()
                                    .isNullOrBlank() || mBind.workModeTypeET.text.toString().trim()
                                    .isNullOrBlank() || mBind.onlineWorkTimeET.text.toString()
                                    .trim()
                                    .isNullOrBlank() || mBind.onlineWorkJGTimeET.text.toString()
                                    .trim().isNullOrBlank()
                            ) {
                                ToastUtils.show("请输入完整信息再操作")
                            } else {
                                var workModeVale = 0
                                for (i in 0 until workModeDec.size) {
                                    if (mBind.workModeTypeET.text.toString()
                                            .trim() == workModeDec.get(i)
                                    ) {
                                        workModeVale = workModeValue[i].toInt()
                                    }
                                }
                                mViewModel.sendedSystemInfo = SystemInfoBean(
                                    mBind.addressET.text.toString().trim().toInt(),
                                    mBind.timeOutSecondET.text.toString().trim().toInt(),
                                    mBind.wakeUpTimeET.text.toString().trim().toInt(),
                                    workModeVale,
                                    mBind.onlineWorkTimeET.text.toString().trim().toInt(),
                                    mBind.onlineWorkJGTimeET.text.toString().trim().toInt()
                                )
                                mViewModel.systemAddress =
                                    mBind.addressET.text.toString().trim().toInt()
                                Log.e("", "")
                                var cmd =
                                    "FF55AA006E" + getAddress() + "4502000000000064" + MyUtil.numberToHexOne(
                                        mBind.addressET.text.toString().trim().toInt()
                                    ) + MyUtil.numberToHexOne(
                                        mBind.timeOutSecondET.text.toString().trim().toInt()
                                    ) + MyUtil.numberToHexOne(
                                        mBind.wakeUpTimeET.text.toString().trim().toInt()
                                    ) + MyUtil.numberToHexOne(
                                        workModeVale
                                    ) + MyUtil.numberToHexTwo(
                                        mBind.onlineWorkTimeET.text.toString().trim().toInt()
                                    ) + MyUtil.numberToHexTwo(
                                        mBind.onlineWorkJGTimeET.text.toString().trim().toInt()
                                    ) + MyUtil.bytes2Hex(mViewModel.otherPackageData) + "000000000000000000000000"
                                mViewModel.sendCommonCMD(
                                    it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                                )
                            }

                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }
                //清空flash
                mBind.clearFlash -> {
                    if (mBind.clearFlash.text.toString() == getString(R.string.clear_flash)) {
                        var countDownTimer = object : CountDownTimer(30000, 1000) {
                            override fun onFinish() {
                                Log.d(TAG, "==倒计时结束")
                                mBind.clearFlash.text = getString(R.string.clear_flash)
                                dialog?.doDismiss()
                            }

                            override fun onTick(millisUntilFinished: Long) {
                                var second = millisUntilFinished / 1000 % 60
                                mBind.clearFlash.text = "" + second + "秒后再操作"

                                Log.e(TAG, "==倒计时" + second + "秒")
                            }
                        }.start()
                        if (HBluetooth.getInstance().isConnected) {
                            HBluetooth.getInstance().sender()?.let { it1 ->
                                dialog = WaitDialog.show("操作中，请勿进行其它操作并等待响应...")
                                mViewModel.clickType = 6
                                var cmd = "FF55AA0004" + getAddress() + "4301"
                                mViewModel.sendCommonCMD(
                                    it1, cmd + CRC16Utils.checkCRC(
                                        MyUtil.hex2Bytes(
                                            cmd
                                        )
                                    )
                                )
                            }
                        } else {
                            ToastUtils.show("请先连接设备后再操作")
                        }
                    } else {
                        ToastUtils.show("请勿频繁点击")
                    }
                }
                //复位
                mBind.reset -> {
                    if (HBluetooth.getInstance().isConnected) {
                        HBluetooth.getInstance().sender()?.let { it1 ->
                            mViewModel.clickType = 1
                            var cmd = "FF55AA0003" + getAddress() + "30"
                            mViewModel.sendCommonCMD(
                                it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                            )
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }
                //关机
                mBind.powerOff -> {
                    if (HBluetooth.getInstance().isConnected) {
                        HBluetooth.getInstance().sender()?.let { it1 ->
                            mViewModel.clickType = 2
                            var cmd = "FF55AA0003" + getAddress() + "31"
                            mViewModel.sendCommonCMD(
                                it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                            )
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }
                //唤醒设备
                mBind.wakeUp -> {
                    mViewModel.continueSendWakeUpCMD = true
                    if (HBluetooth.getInstance().isConnected) {
                        lifecycleScope.launch {
                            var i = 0
                            flow<Int> {
                                while (mViewModel.continueSendWakeUpCMD) {
                                    Log.e("唤醒", "while 唤醒  " + i)
                                    i++
                                    if (i == 20) {
                                        mViewModel.continueSendWakeUpCMD = false
                                    } else {
                                        mViewModel.continueSendWakeUpCMD = true
                                        emit(i)
                                        delay(15)
                                    }

                                }
                            }.collect {
                                Log.e("唤醒", "唤醒  " + it)
                                HBluetooth.getInstance().sender()?.let { it1 ->
                                    mViewModel.clickType = 3
                                    var cmd = "FF55AA0004" + getAddress() + "4001"
                                    delay(15)
                                    mViewModel.sendCommonCMD(
                                        it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                                    )
                                }
                            }

                        }

                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }
                //进入休眠
                mBind.enterSleep -> {
                    if (HBluetooth.getInstance().isConnected) {
                        HBluetooth.getInstance().sender()?.let { it1 ->
                            mViewModel.clickType = 4
                            var cmd = "FF55AA0004" + getAddress() + "4002"
                            mViewModel.sendCommonCMD(
                                it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                            )
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }
                //校时
                mBind.checkTime -> {
                    Log.e("校时", "校时111111 " + HBluetooth.getInstance().isConnected)
                    if (HBluetooth.getInstance().isConnected) {
                        HBluetooth.getInstance().sender()?.let { it1 ->
                            var date = Date()
                            val format = SimpleDateFormat("yyMMddHHmmss")
                            val str = format.format(date)
                            Log.e("校时", "校时str  " + str)
                            var year = MyUtil.numberToHexOne(str.substring(0, 2).toInt())
                            var month = MyUtil.numberToHexOne(str.substring(2, 4).toInt())
                            var day = MyUtil.numberToHexOne(str.substring(4, 6).toInt())
                            var hour = MyUtil.numberToHexOne(str.substring(6, 8).toInt())
                            var minute = MyUtil.numberToHexOne(str.substring(8, 10).toInt())
                            var second = MyUtil.numberToHexOne(str.substring(10, 12).toInt())
                            var time = "" + year + month + day + hour + minute + second
                            Log.e("校时", "校时1111111    " + time)
                            mViewModel.clickType = 5
                            mViewModel.checkTimeCMDSendTime = time
                            var cmd = "FF55AA000A" + getAddress() + "4202$time"
                            mViewModel.sendCommonCMD(
                                it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                            )
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }
                //读取时间
                mBind.readTime -> {
                    Log.e("校时", "校时111111 " + HBluetooth.getInstance().isConnected)
                    if (HBluetooth.getInstance().isConnected) {
                        HBluetooth.getInstance().sender()?.let { it1 ->
                            mViewModel.clickType = 11
                            var cmd = "FF55AA0004" + getAddress() + "4201"
                            mViewModel.sendCommonCMD(
                                it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                            )
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }
                //读取当前存储数量
                mBind.readTotalSize -> {
                    if (HBluetooth.getInstance().isConnected) {
                        HBluetooth.getInstance().sender()?.let { it1 ->
                            mViewModel.clickType = 7
                            var cmd = "FF55AA0003" + getAddress() + "44"
                            mViewModel.sendCommonCMD(
                                it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                            )
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }
                //设备信息
                mBind.deviceInfo -> {
                    if (HBluetooth.getInstance().isConnected) {
                        HBluetooth.getInstance().sender()?.let { it1 ->
                            mViewModel.clickType = 8
                            var cmd = "FF55AA0003" + getAddress() + "47"
                            mViewModel.sendCommonCMD(
                                it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                            )
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }


            }
        }
    }


    override fun onRequestSuccess() {
//        LiveDataEvent.SystemSettingConnectSPPDevice.observe(this, Observer {
//            if (LiveDataEvent.SystemSettingConnectSPPDevice.value?.connect == true) {
//                connectDevice(LiveDataEvent.SystemSettingConnectSPPDevice.value!!.bluetoothDevice as BluetoothDevice)
//            }
//        })
        mViewModel.tipslistData.observe(this, Observer {
            mTipsAdapter.setNewInstance(it)
            mTipsAdapter.notifyDataSetChanged()
            mBind.listRecyclerView.layoutManager?.scrollToPosition(mTipsAdapter.itemCount - 1)
        })
        mViewModel.closeWaitDialog.observe(this, Observer {
            if (it) {
                dialog?.doDismiss()
            }
        })
        mViewModel.updateUI.observe(this, Observer {
            if (it) {
                mViewModel.readedSystemInfo?.let {
                    mBind.addressET.setText("" + it.address)
                    mBind.timeOutSecondET.setText("" + it.outTime)
                    mBind.wakeUpTimeET.setText("" + it.intervalTime)
                    for (i in 0 until workModeValue.size) {
                        if (workModeValue[i].toInt() == it.workMode) {
                            mBind.workModeTypeET.setText("" + workModeDec[i])
                        }
                    }

                    mBind.onlineWorkTimeET.setText("" + it.onlineWorkTime)
                    mBind.onlineWorkJGTimeET.setText("" + it.onlineWorkInterval)
                }

            }
        })
    }

    private fun getAddress(): String {
        return MyUtil.numberToHexOne(mmkv.getInt(ValueKey.DEVICE_ADDRESS, 250))
    }

    private fun connectDevice(bluetoothDevice: BluetoothDevice?) {
        Log.e("connectDevice", "connectDevice    " + bluetoothDevice?.name)
        HBluetooth.getInstance().connect(bluetoothDevice, object : ConnectCallBack {
            override fun onConnecting() {
                Log.e(TAG, "连接中...")
                mViewModel.addMessage("连接中...${bluetoothDevice?.name}")
            }

            override fun onConnected(sender: Sender) {
                Log.e(
                    TAG,
                    "连接成功1111111111111111,isConnected:" + HBluetooth.getInstance().isConnected
                )
                mViewModel.addMessage("连接成功,${bluetoothDevice?.name}")
                //调用发送器发送命令
//                mSender = sender
            }

            override fun onDisConnecting() {
                mViewModel.addMessage("断开连接中...,${bluetoothDevice?.name}")
                Log.e(TAG, "断开连接中...")
            }

            override fun onDisConnected() {
                mViewModel.addMessage("已断开连接,${bluetoothDevice?.name}")
                Log.e(TAG, "已断开连接,isConnected:" + HBluetooth.getInstance().isConnected)
            }

            override fun onError(errorType: Int, errorMsg: String) {
                mViewModel.addMessage("错误类型：$errorType 错误原因：$errorMsg,${bluetoothDevice?.name}")
                Log.e(TAG, "错误类型：$errorType 错误原因：$errorMsg")
            } //低功耗蓝牙才需要BleNotifyCallBack
            //经典蓝牙可以只调两参方法connect(BluetoothDevice device, ConnectCallBack connectCallBack)
        })
    }


    private fun initListener() {
        HBluetooth.getInstance().setReceiver { dataInputStream, result -> //设备发过来的数据将在这里出现
            Log.e(
                "测试返回数据",
                result.size.toString() + "收到蓝牙设备返回数据222222222222222222222222->" + MyUtil.bytes2Hex(
                    result
                )
            )
            lifecycleScope.launch {
                mViewModel.addMessage(
                    "返回数据->" + MyUtil.bytes2Hex(result)
                )
                mViewModel.handleBLEResult(result)
            }

        }
    }


    override fun onDestroy() {
        super.onDestroy()
//        HBluetooth.getInstance().release()
    }

}